package com.util.timerTask;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.Entity.ClickInfo;
import com.Entity.InterestInfo;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import com.util.textProcess.ConnectionPool;
import com.util.textProcess.DecayFunc;
import com.util.textProcess.NLPIR;
import com.util.textProcess.NLPIR.CLibrary;

@Component
public class InterestModel {

	private static CLibrary nLPIR = NLPIR.getInstance();

	static ConnectionPool pool = null;
	static Connection conn;
	static PreparedStatement stmt;
	static Statement sta;

	static {
		// 初始化NLPIR
		int init_flag;
		try {
			init_flag = NLPIR.init_NLPIR();
			if (init_flag == 0) {
				System.out.println("NLPIR初始化失败！");
			} else {
				System.out.println("NLPIR初始化成功！");
			}
			pool = ConnectionPool.getInstance();
			conn = (Connection) pool.getConnection();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void updateInterestModel(int userId, Long newsId)
			throws SQLException, FileNotFoundException, IOException {
		String Content = readNews(newsId);
		String keyword = nLPIR.NLPIR_GetKeyWords(Content, 1, false);
		keyword = keyword.substring(0, keyword.length() - 1);
		List<InterestInfo> interestList = getInterestVector(userId);
		Boolean flag = false;
		for (InterestInfo interest : interestList) {
			// 如果已经存在，则将其权值增加0.2
			if (interest.getInterestName().equals(keyword)) {
				Double decay_weight = DecayFunc.getDecayWeight(interest
						.getModifyTime());
				double weight = ((interest.getInterestWeight() * decay_weight + 0.2) >= 1) ? 1
						: (interest.getInterestWeight() * decay_weight + 0.2);
				interest.setInterestWeight((float) weight);
				flag = true;
				System.out.println("更新" + keyword + "的权值为" + weight);
				updateInterest(interest);
			}
		}
		if (!flag) {
			InterestInfo interest = new InterestInfo();
			interest.setInterestName(keyword);
			interest.setUserId(userId);
			System.out.println("添加" + keyword + "到兴趣模型中！");
			saveInterest(interest);
		}
	}

	// save recnewslist
	public static void saveInterest(InterestInfo interest) throws SQLException {
		String sql = "insert into interestInfo(userId,interestName,interestWeight,isChannel,createTime,modifyTime) values (?,?,0.2,0,?,?)";
		stmt = (PreparedStatement) conn.prepareStatement(sql);
		stmt.setInt(1, interest.getUserId());
		stmt.setString(2, interest.getInterestName());
		stmt.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis()));
		stmt.setTimestamp(4, new java.sql.Timestamp(System.currentTimeMillis()));
		stmt.executeUpdate();
	}

	// update recnewslist
	public static void updateInterest(InterestInfo interest)
			throws SQLException {
		String sql = "update interestInfo set interestWeight=?,modifyTime=? where interestId=?";
		stmt = (PreparedStatement) conn.prepareStatement(sql);
		stmt.setFloat(1, interest.getInterestWeight());
		stmt.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
		stmt.setLong(3, interest.getInterestId());
		stmt.executeUpdate();
	}

	/**
	 * 读取用户兴趣模型向量
	 * 
	 * @param args
	 * @throws SQLException
	 */
	public static List<InterestInfo> getInterestVector(int userid)
			throws SQLException {
		List<InterestInfo> interestList = new ArrayList<InterestInfo>();
		String sql = "SELECT * FROM interestInfo where userId=?";
		stmt = (PreparedStatement) conn.prepareStatement(sql);
		stmt.setInt(1, userid);
		ResultSet rs = stmt.executeQuery();
		while (rs.next()) {
			InterestInfo interestInfo = new InterestInfo();
			interestInfo.setCreateTime(rs.getTimestamp("createTime"));
			interestInfo.setInterestId(rs.getInt("interestId"));
			interestInfo.setInterestName(rs.getString("interestName"));
			interestInfo.setInterestWeight(rs.getFloat("interestWeight"));
			interestInfo.setIsChannel(rs.getShort("isChannel"));
			interestInfo.setModifyTime(rs.getTimestamp("modifyTime"));
			interestInfo.setUserId(rs.getInt("userId"));
			interestList.add(interestInfo);
		}
		return interestList;
	}

	// get ClickList
	public static List<ClickInfo> getClickList(Integer userid)
			throws SQLException {
		List<ClickInfo> clickInfoList = new ArrayList<ClickInfo>();
		String sql = "SELECT * FROM clickInfo WHERE userId=?";
		stmt = (PreparedStatement) conn.prepareStatement(sql);
		stmt.setInt(1, userid);
		ResultSet rs = stmt.executeQuery();
		while (rs.next()) {
			ClickInfo clickInfo = new ClickInfo();
			clickInfo.setClickId(rs.getLong("clickId"));
			clickInfo.setClickNum(rs.getInt("clickNum"));
			clickInfo.setClickTime(rs.getDate("clickTime"));
			clickInfo.setInfoId(rs.getLong("infoId"));
			clickInfo.setUserId(rs.getInt("userId"));
			clickInfoList.add(clickInfo);
		}
		return clickInfoList;
	}

	// read news
	public static String readNews(long newsid) throws FileNotFoundException,
			IOException, SQLException {
		String sql = "SELECT infoId,contentBody FROM knowledgeInfo WHERE infoId=?";
		stmt = (PreparedStatement) conn.prepareStatement(sql);
		stmt.setLong(1, newsid);
		ResultSet rs = stmt.executeQuery();
		String content = "";
		while (rs.next()) {
			content = rs.getString("contentBody");
		}
		return content;
	}

	/**
	 * 读取所有用户兴趣模型
	 * 
	 * @param args
	 * @throws SQLException
	 */
	public static List<InterestInfo> getAllInterestVector() throws SQLException {
		List<InterestInfo> interestList = new ArrayList<InterestInfo>();
		String sql = "SELECT * FROM interestInfo where isChannel=0";
		stmt = (PreparedStatement) conn.prepareStatement(sql);
		ResultSet rs = stmt.executeQuery();
		while (rs.next()) {
			InterestInfo interestInfo = new InterestInfo();
			interestInfo.setCreateTime(rs.getTimestamp("createTime"));
			interestInfo.setInterestId(rs.getInt("interestId"));
			interestInfo.setInterestName(rs.getString("interestName"));
			interestInfo.setInterestWeight(rs.getFloat("interestWeight"));
			interestInfo.setIsChannel(rs.getShort("isChannel"));
			interestInfo.setModifyTime(rs.getTimestamp("modifyTime"));
			interestInfo.setUserId(rs.getInt("userId"));
			interestList.add(interestInfo);
		}
		return interestList;
	}

	/**
	 * 读取所有用户兴趣模型
	 * 
	 * @param args
	 * @throws SQLException
	 */
	public static void deleteInterest(int interestId) throws SQLException {
		String sql = "DELETE FROM interestInfo where interestId=?";
		stmt = (PreparedStatement) conn.prepareStatement(sql);
		stmt.setInt(1, interestId);
		int rs = stmt.executeUpdate();
		if (rs > 0) {
			System.out.println("删除了ID为" + interestId + "的兴趣特征项！");
		}
	}

	public static void executeDecayInterestModel() throws SQLException {
		// TODO Auto-generated method stub
		List<InterestInfo> interestList = getAllInterestVector();
		for (InterestInfo interestInfo : interestList) {
			Timestamp modiyTime = interestInfo.getModifyTime();
			Double decay_weight = DecayFunc.getDecayWeight(modiyTime);
			Double weight = decay_weight * (interestInfo.getInterestWeight());
			// System.out.println("weight……"+weight);
			if (weight < 0.1) {
				deleteInterest(interestInfo.getInterestId());
			}
		}
	}
}
